<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/sj-request'
import ExamPlanForm from '@/components/sj/ExamPlanForm.vue'
import BigQuestionForm from '@/components/sj/BigQuestionForm.vue'
import KnowledgePointTree from '@/components/sj/KnowledgePointTree.vue'
import KnowledgePointForm from '@/components/sj/KnowledgePointForm.vue'
import SubjectQuestionList from '@/components/sj/SubjectQuestionList.vue'
import QuestionTypeManagement from '@/components/sj/QuestionTypeManagement.vue'
import { usetikuUserStore } from '@/stores/sj-user'
import { ROLES, hasFeaturePermission } from '@/utils/permission'

const route = useRoute()
const router = useRouter()
const userStore = usetikuUserStore()

// 获取用户信息
const userInfo = computed(() => userStore.userInfo)

// 检查用户是否有权限执行特定功能
const canAccessFeature = (feature) => {
  return hasFeaturePermission(userInfo.value, feature)
}

// 获取路由参数中的学科ID
const subjectId = ref(route.params.id)

// 学科信息
const subject = ref({
  id: 0,
  name: '',
  code: '',
  description: ''
})

// 当前激活的选项卡
// 根据用户角色设置默认选项卡
// 教师角色默认显示试题管理，其他角色默认显示组卷管理
const activeTab = ref(userInfo.value.roleName === ROLES.TEACHER ? 'question' : 'paper')

// 知识点管理相关
const knowledgePointRefresh = ref(false)
const selectedKnowledgePoint = ref(null)

// 大题列表
const bigQuestionList = ref([])
// 大题搜索关键词
const bigQuestionKeyword = ref('')
// 大题分页参数
const bigQuestionPagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 组卷方案列表
const paperSchemeList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取学科详情
const fetchSubjectDetail = async () => {
  try {
    loading.value = true
    const res = await request({
      url: `/subject/${subjectId.value}`,
      method: 'get'
    })
    
    if (res.code === 200 && res.data) {
      subject.value = res.data
    } else {
      // 如果API请求失败或返回空数据，设置默认值
      subject.value = {
        id: subjectId.value,
        name: '未知学科',
        code: 'SUBJECT_' + subjectId.value,
        description: '暂无描述'
      }
      console.error('获取学科详情返回异常:', res)
      ElMessage.warning('获取学科详情异常，显示默认数据')
    }
  } catch (error) {
    console.error('获取学科详情失败:', error)
    ElMessage.error('获取学科详情失败')
    // 设置默认值
    subject.value = {
      id: subjectId.value,
      name: '未知学科',
      code: 'SUBJECT_' + subjectId.value,
      description: '暂无描述'
    }
  }
}

// 获取组卷方案列表
const fetchPaperSchemes = async () => {
  loading.value = true
  try {
    // 调用后端API获取组卷方案列表
    const res = await request({
      url: '/exam-plan/page',
      method: 'get',
      params: {
        subjectId: subjectId.value,
        page: pagination.value.currentPage,
        size: pagination.value.pageSize,
        keyword: searchKeyword.value
      }
    })
    
    if (res.code === 200 && res.data) {
      paperSchemeList.value = res.data.records || []
      pagination.value.total = res.data.total || 0
    } else {
      // 如果API请求失败，使用模拟数据
      const mockData = {
        total: 8,
        records: [
          { id: 1, name: '期末考试方案', description: '适用于期末考试的组卷方案', createTime: '2023-05-15 10:30:00', questionCount: 30, totalScore: 100 },
          { id: 2, name: '月考方案', description: '适用于月考的组卷方案', createTime: '2023-06-20 14:45:00', questionCount: 25, totalScore: 100 },
          { id: 3, name: '单元测试方案', description: '适用于单元测试的组卷方案', createTime: '2023-07-10 09:15:00', questionCount: 20, totalScore: 60 },
          { id: 4, name: '模拟考试方案', description: '适用于模拟考试的组卷方案', createTime: '2023-08-05 16:30:00', questionCount: 35, totalScore: 150 }
        ]
      }
      
      paperSchemeList.value = mockData.records
      pagination.value.total = mockData.total
      console.warn('使用模拟数据替代API响应')
    }
  } catch (error) {
    console.error('获取组卷方案列表失败:', error)
    ElMessage.error('获取组卷方案列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchPaperSchemes()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchPaperSchemes()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchPaperSchemes()
}

// 处理重置筛选条件
const handleReset = () => {
  searchKeyword.value = ''
  pagination.value.currentPage = 1
  fetchPaperSchemes()
}

// 方案对话框控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const examPlanFormRef = ref(null)

// 当前编辑的方案
const currentExamPlan = ref({})

// 新增组卷方案
const handleAddScheme = () => {
  addDialogVisible.value = true
}

// 处理新增方案提交
const handleAddSubmit = async (formData) => {
  try {
    loading.value = true
    // 获取当前登录用户信息
    let userInfo = {id: 0}; // 默认用户ID为0
    try {
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr && userInfoStr !== 'undefined') {
        userInfo = JSON.parse(userInfoStr);
      } else {
        console.warn('localStorage中的userInfo为空或undefined');
      }
    } catch (error) {
      console.error('解析用户信息失败:', error);
      ElMessage.warning('获取用户信息失败，将使用默认用户ID');
    }
    // 添加创建者ID和用户ID
    formData.creatorId = userInfo.id || 0; // 确保即使userInfo中没有id也能提供默认值
    formData.userId = userInfo.id || 0; // 同时设置userId字段
    
    const res = await request({
      url: '/exam-plan',
      method: 'post',
      data: formData
    })
    
    if (res.code === 200) {
      ElMessage.success('新增组卷方案成功')
      addDialogVisible.value = false
      // 重新加载组卷方案列表
      fetchPaperSchemes()
    } else {
      ElMessage.error(res.message || '新增组卷方案失败')
    }
  } catch (error) {
    console.error('新增组卷方案失败:', error)
    ElMessage.error('新增组卷方案失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理新增方案取消
const handleAddCancel = () => {
  addDialogVisible.value = false
  // 重置表单
  if (examPlanFormRef.value) {
    examPlanFormRef.value.resetForm()
  }
}

// 编辑组卷方案
const handleEditScheme = (row) => {
  currentExamPlan.value = JSON.parse(JSON.stringify(row))
  editDialogVisible.value = true
}

// 处理编辑方案提交
const handleEditSubmit = async (formData) => {
  try {
    loading.value = true
    // 保留原始ID和userId
    formData.id = currentExamPlan.value.id
    
    // 获取当前登录用户信息
    let userInfo = {id: 0}; // 默认用户ID为0
    try {
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr && userInfoStr !== 'undefined') {
        userInfo = JSON.parse(userInfoStr);
      } else {
        console.warn('localStorage中的userInfo为空或undefined');
      }
    } catch (error) {
      console.error('解析用户信息失败:', error);
      ElMessage.warning('获取用户信息失败，将使用默认用户ID');
    }
    
    // 确保保留原始userId，如果没有则使用当前登录用户ID
    formData.userId = currentExamPlan.value.userId || userInfo.id || 0;
    
    const res = await request({
      url: '/exam-plan',
      method: 'put',
      data: formData
    })
    
    if (res.code === 200) {
      ElMessage.success('更新组卷方案成功')
      editDialogVisible.value = false
      // 重新加载组卷方案列表
      fetchPaperSchemes()
    } else {
      ElMessage.error(res.message || '更新组卷方案失败')
    }
  } catch (error) {
    console.error('更新组卷方案失败:', error)
    ElMessage.error('更新组卷方案失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理编辑方案取消
const handleEditCancel = () => {
  editDialogVisible.value = false
  currentExamPlan.value = {}
}

// 预览组卷方案
const handlePreviewScheme = (row) => {
  currentExamPlan.value = row
  previewDialogVisible.value = true
}

// 删除组卷方案
const handleDeleteScheme = (id, name) => {
  ElMessageBox.confirm(`确定要删除组卷方案「${name}」吗？删除后不可恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const res = await request({
        url: `/exam-plan/${id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchPaperSchemes()
      } else {
        ElMessage.error(res.message || '删除组卷方案失败')
      }
    } catch (error) {
      console.error('删除组卷方案失败:', error)
      ElMessage.error('删除组卷方案失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

// 获取大题列表
const fetchBigQuestions = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/big-question/page',
      method: 'get',
      params: {
        page: bigQuestionPagination.value.currentPage,
        size: bigQuestionPagination.value.pageSize,
        subjectId: subjectId.value,
        keyword: bigQuestionKeyword.value
      }
    })
    
    if (res.code === 200 && res.data) {
      bigQuestionList.value = res.data.records || []
      bigQuestionPagination.value.total = res.data.total || 0
    } else {
      ElMessage.warning(res.message || '获取大题列表失败')
    }
  } catch (error) {
    console.error('获取大题列表失败:', error)
    ElMessage.error('获取大题列表失败')
  } finally {
    loading.value = false
  }
}

// 处理大题页码变化
const handleBigQuestionCurrentChange = (page) => {
  bigQuestionPagination.value.currentPage = page
  fetchBigQuestions()
}

// 处理大题每页条数变化
const handleBigQuestionSizeChange = (size) => {
  bigQuestionPagination.value.pageSize = size
  bigQuestionPagination.value.currentPage = 1
  fetchBigQuestions()
}

// 处理大题搜索
const handleBigQuestionSearch = () => {
  bigQuestionPagination.value.currentPage = 1
  fetchBigQuestions()
}

// 处理大题重置筛选条件
const handleBigQuestionReset = () => {
  bigQuestionKeyword.value = ''
  bigQuestionPagination.value.currentPage = 1
  fetchBigQuestions()
}

// 新增大题对话框控制
const addBigQuestionDialogVisible = ref(false)
const bigQuestionFormRef = ref(null)

// 编辑大题对话框控制
const editBigQuestionDialogVisible = ref(false)
const currentBigQuestion = ref({})

// 新增大题
const handleAddBigQuestion = () => {
  addBigQuestionDialogVisible.value = true
}

// 编辑大题
const handleEditBigQuestion = (row) => {
  currentBigQuestion.value = { ...row }
  editBigQuestionDialogVisible.value = true
}

// 处理新增大题提交
const handleAddBigQuestionSubmit = async (formData) => {
  try {
    loading.value = true
    const res = await request({
      url: '/big-question',
      method: 'post',
      data: formData
    })
    
    if (res.code === 200) {
      ElMessage.success('新增大题成功')
      addBigQuestionDialogVisible.value = false
      // 重新加载大题列表
      fetchBigQuestions()
    } else {
      ElMessage.error(res.message || '新增大题失败')
    }
  } catch (error) {
    console.error('新增大题失败:', error)
    ElMessage.error('新增大题失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理编辑大题提交
const handleEditBigQuestionSubmit = async (formData) => {
  try {
    loading.value = true
    const res = await request({
      url: '/big-question',
      method: 'put',
      data: formData
    })
    
    if (res.code === 200) {
      ElMessage.success('更新大题成功')
      editBigQuestionDialogVisible.value = false
      // 重新加载大题列表
      fetchBigQuestions()
    } else {
      ElMessage.error(res.message || '更新大题失败')
    }
  } catch (error) {
    console.error('更新大题失败:', error)
    ElMessage.error('更新大题失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理新增/编辑大题取消
const handleBigQuestionCancel = () => {
  addBigQuestionDialogVisible.value = false
  editBigQuestionDialogVisible.value = false
}

// 删除大题
const handleDeleteBigQuestion = (id, name) => {
  ElMessageBox.confirm(`确定要删除大题「${name}」吗？删除后不可恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const res = await request({
        url: `/big-question/${id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除大题成功')
        // 重新加载大题列表
        fetchBigQuestions()
      } else {
        ElMessage.error(res.message || '删除大题失败')
      }
    } catch (error) {
      console.error('删除大题失败:', error)
      ElMessage.error('删除大题失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}



// 处理知识点选择
const handleKnowledgePointSelect = (knowledgePoint) => {
  selectedKnowledgePoint.value = knowledgePoint
}

// 处理知识点表单提交成功
const handleKnowledgePointSuccess = () => {
  // 刷新知识点树
  knowledgePointRefresh.value = true
  setTimeout(() => {
    knowledgePointRefresh.value = false
  }, 100)
  // 清空选中的知识点
  selectedKnowledgePoint.value = null
}

// 处理知识点表单取消
const handleKnowledgePointCancel = () => {
  selectedKnowledgePoint.value = null
}

// 处理知识点刷新
const handleKnowledgePointRefresh = () => {
  // 刷新知识点树
  knowledgePointRefresh.value = true
  setTimeout(() => {
    knowledgePointRefresh.value = false
  }, 100)
}

// 导出组卷方案
const handleExportScheme = (id) => {
  ElMessage.info('正在准备导出，请稍候...')
  loading.value = true
  
  // 获取API基础URL
  const baseURL = import.meta.env.VITE_API_BASE_URL || '/api'
  // 获取token
  const token = localStorage.getItem('token')
  
  // 创建一个原生的XMLHttpRequest来处理文件下载
  const xhr = new XMLHttpRequest()
  xhr.open('GET', `${baseURL}/exam-plan/export/${id}`, true)
  xhr.responseType = 'blob'
  
  // 设置认证头
  if (token) {
    xhr.setRequestHeader('Authorization', `Bearer ${token}`)
  }
  
  xhr.onload = function() {
    if (xhr.status === 200) {
      // 创建Blob对象
      const blob = new Blob([xhr.response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      
      // 设置文件名
      const contentDisposition = xhr.getResponseHeader('content-disposition')
      let fileName = `组卷方案_${id}.xlsx`
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(/filename=([^;]+)/)
        if (fileNameMatch && fileNameMatch[1]) {
          fileName = decodeURIComponent(fileNameMatch[1])
        }
      }
      
      link.download = fileName
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
      
      ElMessage.success('导出成功')
    } else {
      console.error('导出失败:', xhr.statusText)
      ElMessage.error('导出失败，请重试')
    }
    loading.value = false
  }
  
  xhr.onerror = function() {
    console.error('导出请求失败')
    ElMessage.error('导出失败，请检查网络连接')
    loading.value = false
  }
  
  xhr.send()
}

// 处理选项卡切换
const handleTabChange = (tabName) => {
  // 根据选项卡名称加载对应数据
  if (tabName === 'paper') {
    fetchPaperSchemes()
  } else if (tabName === 'section') {
    fetchBigQuestions()
  } else if (tabName === 'questionType') {
    // 题型管理选项卡不需要额外处理，组件内部会自动加载数据
  } else if (tabName === 'knowledge') {
    // 知识点管理选项卡不需要额外处理，组件内部会自动加载数据
  } else if (tabName === 'question') {
    // 试题管理选项卡不需要额外处理，组件内部会自动加载数据
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSubjectDetail()
  fetchPaperSchemes()
  // 无论初始选项卡是什么，都加载大题列表，确保数据已准备好
  fetchBigQuestions()
})
</script>

<template>
  <div>
    <!-- 页面顶部导航栏 -->
    <div class="page-header">
      <el-button type="primary" class="back-button" @click="router.push('/home/subject')">返回</el-button>
    </div>
    <!-- 学科信息头部 -->
    <div class="subject-header">
      <div class="subject-icon">
        {{ subject.name.charAt(0).toUpperCase() }}
      </div>
      <div class="subject-info">
        <h2 class="subject-name">{{ subject.name }}</h2>
        <p class="subject-description">{{ subject.description }}</p>
      </div>
    </div>
    <!-- 功能选项卡 -->
    <el-tabs v-model="activeTab" class="subject-tabs" @tab-change="handleTabChange">
      <!-- 组卷管理选项卡 -->
      <el-tab-pane label="组卷管理" name="paper">
        <!-- 搜索和筛选区域 -->
        <el-card class="filter-container" shadow="never">
          <el-form :inline="true" class="filter-form">
            <el-form-item label="关键词">
              <el-input
                v-model="searchKeyword"
                placeholder="方案名称/描述"
                clearable
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 组卷方案列表 -->
        <el-card class="list-container" shadow="never">
          <template #header>
            <div class="card-header">
              <span>组卷方案列表</span>
              <el-button type="primary" @click="handleAddScheme">新增方案</el-button>
            </div>
          </template>
          <el-table
            v-loading="loading"
            :data="paperSchemeList"
            border
            style="width: 100%"
          >
            <el-table-column label="序号" width="80">
              <template #default="{$index}">
                {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="方案名称" width="150" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="questionCount" label="试题数量" width="100" />
            <el-table-column label="总分" width="80">
              <template #default="{row}">
                {{ row.totalScore || 0 }}
              </template>
            </el-table-column>
            <el-table-column label="创建人" width="80">
              <template #default="{row}">
                {{ row.userName || "无" }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template #default="{row}">
                {{ row.createTime ? new Date(row.createTime).toLocaleString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit'
                }).replace(/\//g, '-') : '' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="260" fixed="right">
              <template #default="{row}">
                <el-button link type="primary" size="small" @click="handleEditScheme(row)">编辑</el-button>
                <el-button link type="primary" size="small" @click="handlePreviewScheme(row)">预览</el-button>
                <el-button link type="success" size="small" @click="handleExportScheme(row.id)">导出</el-button>
                <el-button 
                  link 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteScheme(row.id, row.name)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-tab-pane>
      
      <!-- 大题管理选项卡 - 所有角色可见，但教师只读 -->
      <el-tab-pane label="大题管理" name="section">
        <!-- 搜索和筛选区域 -->
        <el-card class="filter-container" shadow="never">
          <el-form :inline="true" class="filter-form">
            <el-form-item label="关键词">
              <el-input
                v-model="bigQuestionKeyword"
                placeholder="大题名称"
                clearable
                @keyup.enter="handleBigQuestionSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleBigQuestionSearch">搜索</el-button>
              <el-button @click="handleBigQuestionReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 大题列表 -->
        <el-card class="list-container" shadow="never">
          <template #header>
            <div class="card-header">
              <span>大题列表</span>
              <el-button v-if="userInfo.roleName === ROLES.ADMIN || userInfo.roleName === ROLES.SUBJECT_LEADER" type="primary" @click="handleAddBigQuestion">新增大题</el-button>
            </div>
          </template>
          
          <el-table
            v-loading="loading"
            :data="bigQuestionList"
            border
            style="width: 100%"
          >
            <el-table-column label="序号" width="80">
              <template #default="{$index}">
                {{ (bigQuestionPagination.currentPage - 1) * bigQuestionPagination.pageSize + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="大题名称" min-width="150" />
            <el-table-column prop="subjectName" label="所属学科" width="150" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{row}">
                <template v-if="userInfo.roleName === ROLES.ADMIN || userInfo.roleName === ROLES.SUBJECT_LEADER">
                  <el-button link type="primary" size="small" @click="handleEditBigQuestion(row)">编辑</el-button>
                  <el-button 
                    link 
                    type="danger" 
                    size="small" 
                    @click="handleDeleteBigQuestion(row.id, row.name)"
                  >
                    删除
                  </el-button>
                </template>
                <template v-else>
                  <span class="text-muted">无操作权限</span>
                </template>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="bigQuestionPagination.currentPage"
              v-model:page-size="bigQuestionPagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="bigQuestionPagination.total"
              @size-change="handleBigQuestionSizeChange"
              @current-change="handleBigQuestionCurrentChange"
            />
          </div>
        </el-card>
      </el-tab-pane>
      
      <!-- 试题管理选项卡 - 所有角色可见 -->
      <el-tab-pane label="试题管理" name="question">
        <subject-question-list :subject-id="Number(subjectId)" />
      </el-tab-pane>
      
      <!-- 题型管理选项卡 - 所有角色可见，但只有管理员可操作 -->
      <el-tab-pane 
        label="题型管理" 
        name="questionType"
      >
        <question-type-management :subject-id="Number(subjectId)" :readonly="userInfo.roleName === ROLES.TEACHER" />
      </el-tab-pane>
      
      <!-- 知识点管理选项卡 - 所有角色可见，但只有管理员和学科组长可操作 -->
      <el-tab-pane 
        label="知识点管理" 
        name="knowledge"
      >
        <div class="knowledge-management-container">
          <!-- 左侧知识点树 -->
          <div class="knowledge-tree-panel">
            <KnowledgePointTree 
              :subject-id="Number(subjectId)" 
              :refresh="knowledgePointRefresh" 
              :readonly="userInfo.roleName === ROLES.TEACHER"
              @select="handleKnowledgePointSelect"
              @refresh="handleKnowledgePointRefresh"
            />
          </div>
          
          <!-- 右侧知识点表单 -->
          <div class="knowledge-form-panel" v-if="selectedKnowledgePoint">
            <div class="panel-header">
              <h3>{{ selectedKnowledgePoint.isNew ? '新增知识点' : (selectedKnowledgePoint.isEdit ? '编辑知识点' : '知识点详情') }}</h3>
            </div>
            <div class="panel-content">
              <KnowledgePointForm 
                :subject-id="Number(subjectId)" 
                :knowledge-point="selectedKnowledgePoint" 
                :is-edit="(selectedKnowledgePoint.isEdit || selectedKnowledgePoint.isNew) && userInfo.roleName !== ROLES.TEACHER" 
                :readonly="userInfo.roleName === ROLES.TEACHER"
                @success="handleKnowledgePointSuccess" 
                @cancel="handleKnowledgePointCancel"
              />
            </div>
          </div>
          
          <!-- 右侧空状态 -->
          <div class="knowledge-form-panel empty-panel" v-else>
            <el-empty description="请选择或添加知识点" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

  
  <!-- 新增组卷方案对话框 -->
  <el-dialog
    v-model="addDialogVisible"
    title="新增组卷方案"
    width="70%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <ExamPlanForm
      ref="examPlanFormRef"
      :subject-id="Number(subjectId)"
      @success="handleAddSubmit"
      @cancel="handleAddCancel"
    />
  </el-dialog>
  
  <!-- 编辑组卷方案对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑组卷方案"
    width="80%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <ExamPlanForm
      ref="examPlanFormRef"
      :subject-id="Number(subjectId)"
      :exam-plan="currentExamPlan"
      :is-edit="true"
      @success="handleEditSubmit"
      @cancel="handleEditCancel"
    />
  </el-dialog>
  
  <!-- 预览组卷方案对话框 -->
  <el-dialog
    v-model="previewDialogVisible"
    title="组卷方案预览"
    width="60%"
  >
    <div class="preview-container">
      <h2 class="preview-title">{{ currentExamPlan.name }}</h2>
      <div class="preview-info">
        <p><strong>描述：</strong>{{ currentExamPlan.description || '无' }}</p>
        <p><strong>试题数量：</strong>{{ currentExamPlan.questionCount || 0 }}</p>
        <p><strong>总分：</strong>{{ currentExamPlan.totalScore || 0 }}</p>
        <p><strong>创建人：</strong>{{ currentExamPlan.userName || "无" }}</p>
        <p><strong>创建时间：</strong>{{ currentExamPlan.createTime ? new Date(currentExamPlan.createTime).toLocaleString() : '未知' }}</p>
      </div>
      
      <h3 class="preview-subtitle">方案详情</h3>
      <el-table :data="currentExamPlan.details || []" border style="width: 100%">
        <el-table-column prop="questionOrder" label="序号" width="80" />
        <el-table-column prop="bigQuestionName" label="大题" width="150" />
        <el-table-column prop="questionTypeName" label="题型" width="150" />
        <el-table-column label="难度" width="100">
          <template #default="{row}">
            <el-tag 
              :type="row.hardLevel === '易' || row.hardLevel === 'EASY' ? 'success' : (row.hardLevel === '中' || row.hardLevel === 'MEDIUM' ? 'warning' : 'danger')"
            >
              {{ row.hardLevel === '易' || row.hardLevel === 'EASY' ? '容易' : (row.hardLevel === '中' || row.hardLevel === 'MEDIUM' ? '中等' : '困难') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="knowledgePointName" label="知识点" width="150" />
        <el-table-column prop="score" label="分值" width="80" />
      </el-table>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 新增大题对话框 -->
  <el-dialog
    v-model="addBigQuestionDialogVisible"
    title="新增大题"
    width="50%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <BigQuestionForm
      ref="bigQuestionFormRef"
      :subject-id="Number(subjectId)"
      @success="handleAddBigQuestionSubmit"
      @cancel="handleBigQuestionCancel"
    />
  </el-dialog>
  
  <!-- 编辑大题对话框 -->
  <el-dialog
    v-model="editBigQuestionDialogVisible"
    title="编辑大题"
    width="50%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <BigQuestionForm
      ref="bigQuestionFormRef"
      :subject-id="Number(subjectId)"
      :big-question="currentBigQuestion"
      :is-edit="true"
      @success="handleEditBigQuestionSubmit"
      @cancel="handleBigQuestionCancel"
    />
  </el-dialog>
</div>
  </template>

<style scoped>
.subject-detail-container {
  padding: 20px;
}

.subject-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.subject-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36px;
  font-weight: bold;
  margin-right: 20px;
}

.subject-info {
  flex: 1;
}

.subject-name {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.subject-description {
  margin: 0;
  color: #606266;
}

.subject-tabs {
  margin-top: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.list-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.placeholder-content {
  padding: 40px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 知识点管理样式 */
.knowledge-management-container {
  display: flex;
  height: calc(100vh - 300px);
  min-height: 500px;
  gap: 20px;
}

.knowledge-tree-panel {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.knowledge-form-panel {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  overflow: auto;
}

.panel-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.panel-content {
  padding: 10px 0;
}

.empty-panel {
  display: flex;
  justify-content: center;
  align-items: center;
}
.preview-container {
  padding: 20px;
}

.preview-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.preview-subtitle {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  color: #303133;
}

.preview-info {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.preview-info p {
  margin: 8px 0;
  line-height: 1.5;
}

/* 页面顶部导航栏样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 15px;
}
.back-button {
  margin-left: auto;
}
</style>